<template>
  <div class="settings-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>系统设置</h3>
        </div>
      </template>

      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <!-- 基本设置 -->
        <el-tab-pane label="基本设置" name="basic">
          <div class="tab-content">
            <el-form :model="basicSettings" :rules="basicRules" ref="basicFormRef" label-width="150px">
              <el-form-item label="系统名称" prop="systemName">
                <el-input v-model="basicSettings.systemName" placeholder="请输入系统名称" />
              </el-form-item>
              
              <el-form-item label="系统版本" prop="systemVersion">
                <el-input v-model="basicSettings.systemVersion" placeholder="请输入系统版本" />
              </el-form-item>
              
              <el-form-item label="公司名称" prop="companyName">
                <el-input v-model="basicSettings.companyName" placeholder="请输入公司名称" />
              </el-form-item>
              
              <el-form-item label="公司地址" prop="companyAddress">
                <el-input v-model="basicSettings.companyAddress" placeholder="请输入公司地址" />
              </el-form-item>
              
              <el-form-item label="联系电话" prop="companyPhone">
                <el-input v-model="basicSettings.companyPhone" placeholder="请输入联系电话" />
              </el-form-item>
              
              <el-form-item label="邮箱地址" prop="companyEmail">
                <el-input v-model="basicSettings.companyEmail" placeholder="请输入邮箱地址" />
              </el-form-item>
              
              <el-form-item label="网站地址" prop="companyWebsite">
                <el-input v-model="basicSettings.companyWebsite" placeholder="请输入网站地址" />
              </el-form-item>
              
              <el-form-item label="系统Logo" prop="systemLogo">
                <el-upload
                  class="logo-uploader"
                  :action="uploadUrl"
                  :show-file-list="false"
                  :on-success="handleLogoSuccess"
                  :before-upload="beforeLogoUpload"
                >
                  <img v-if="basicSettings.systemLogo" :src="basicSettings.systemLogo" class="logo" />
                  <el-icon v-else class="logo-uploader-icon"><Plus /></el-icon>
                </el-upload>
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" @click="saveBasicSettings" :loading="saveLoading">
                  保存设置
                </el-button>
                <el-button @click="resetBasicSettings">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>

        <!-- 业务设置 -->
        <el-tab-pane label="业务设置" name="business">
          <div class="tab-content">
            <el-form :model="businessSettings" :rules="businessRules" ref="businessFormRef" label-width="150px">
              <el-divider content-position="left">库存设置</el-divider>
              
              <el-form-item label="默认仓库" prop="defaultWarehouse">
                <el-select v-model="businessSettings.defaultWarehouse" placeholder="请选择默认仓库" style="width: 100%">
                  <el-option label="主仓库" value="1" />
                  <el-option label="分仓库A" value="2" />
                  <el-option label="分仓库B" value="3" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="库存预警阈值" prop="stockWarningThreshold">
                <el-input-number
                  v-model="businessSettings.stockWarningThreshold"
                  :min="0"
                  :max="1000"
                  style="width: 100%"
                />
                <span class="form-tip">当库存低于此数量时发出预警</span>
              </el-form-item>
              
              <el-form-item label="自动生成编码" prop="autoGenerateCode">
                <el-switch v-model="businessSettings.autoGenerateCode" />
                <span class="form-tip">是否自动生成商品、供应商、客户编码</span>
              </el-form-item>
              
              <el-divider content-position="left">订单设置</el-divider>
              
              <el-form-item label="订单号前缀" prop="orderPrefix">
                <el-input v-model="businessSettings.orderPrefix" placeholder="请输入订单号前缀" />
                <span class="form-tip">如：PO（采购订单）、SO（销售订单）</span>
              </el-form-item>
              
              <el-form-item label="订单有效期" prop="orderValidityDays">
                <el-input-number
                  v-model="businessSettings.orderValidityDays"
                  :min="1"
                  :max="365"
                  style="width: 100%"
                />
                <span class="form-tip">订单有效天数</span>
              </el-form-item>
              
              <el-form-item label="自动确认订单" prop="autoConfirmOrder">
                <el-switch v-model="businessSettings.autoConfirmOrder" />
                <span class="form-tip">是否自动确认新创建的订单</span>
              </el-form-item>
              
              <el-divider content-position="left">财务设置</el-divider>
              
              <el-form-item label="默认币种" prop="defaultCurrency">
                <el-select v-model="businessSettings.defaultCurrency" placeholder="请选择默认币种" style="width: 100%">
                  <el-option label="人民币 (CNY)" value="CNY" />
                  <el-option label="美元 (USD)" value="USD" />
                  <el-option label="欧元 (EUR)" value="EUR" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="税率设置" prop="taxRate">
                <el-input-number
                  v-model="businessSettings.taxRate"
                  :min="0"
                  :max="100"
                  :precision="2"
                  style="width: 100%"
                />
                <span class="form-tip">默认税率（%）</span>
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" @click="saveBusinessSettings" :loading="saveLoading">
                  保存设置
                </el-button>
                <el-button @click="resetBusinessSettings">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>

        <!-- 安全设置 -->
        <el-tab-pane label="安全设置" name="security">
          <div class="tab-content">
            <el-form :model="securitySettings" :rules="securityRules" ref="securityFormRef" label-width="150px">
              <el-divider content-position="left">密码策略</el-divider>
              
              <el-form-item label="密码最小长度" prop="passwordMinLength">
                <el-input-number
                  v-model="securitySettings.passwordMinLength"
                  :min="6"
                  :max="20"
                  style="width: 100%"
                />
              </el-form-item>
              
              <el-form-item label="密码复杂度" prop="passwordComplexity">
                <el-checkbox-group v-model="securitySettings.passwordComplexity">
                  <el-checkbox label="uppercase">包含大写字母</el-checkbox>
                  <el-checkbox label="lowercase">包含小写字母</el-checkbox>
                  <el-checkbox label="numbers">包含数字</el-checkbox>
                  <el-checkbox label="symbols">包含特殊字符</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              
              <el-form-item label="密码有效期" prop="passwordExpiryDays">
                <el-input-number
                  v-model="securitySettings.passwordExpiryDays"
                  :min="0"
                  :max="365"
                  style="width: 100%"
                />
                <span class="form-tip">0表示永不过期</span>
              </el-form-item>
              
              <el-divider content-position="left">登录设置</el-divider>
              
              <el-form-item label="登录失败锁定" prop="loginLockEnabled">
                <el-switch v-model="securitySettings.loginLockEnabled" />
              </el-form-item>
              
              <el-form-item label="最大失败次数" prop="maxLoginAttempts">
                <el-input-number
                  v-model="securitySettings.maxLoginAttempts"
                  :min="3"
                  :max="10"
                  style="width: 100%"
                />
                <span class="form-tip">超过此次数将锁定账户</span>
              </el-form-item>
              
              <el-form-item label="锁定时间" prop="lockoutDuration">
                <el-input-number
                  v-model="securitySettings.lockoutDuration"
                  :min="5"
                  :max="60"
                  style="width: 100%"
                />
                <span class="form-tip">锁定时间（分钟）</span>
              </el-form-item>
              
              <el-form-item label="会话超时" prop="sessionTimeout">
                <el-input-number
                  v-model="securitySettings.sessionTimeout"
                  :min="10"
                  :max="480"
                  style="width: 100%"
                />
                <span class="form-tip">会话超时时间（分钟）</span>
              </el-form-item>
              
              <el-divider content-position="left">数据安全</el-divider>
              
              <el-form-item label="数据加密" prop="dataEncryption">
                <el-switch v-model="securitySettings.dataEncryption" />
                <span class="form-tip">是否对敏感数据进行加密存储</span>
              </el-form-item>
              
              <el-form-item label="操作日志" prop="operationLog">
                <el-switch v-model="securitySettings.operationLog" />
                <span class="form-tip">是否记录用户操作日志</span>
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" @click="saveSecuritySettings" :loading="saveLoading">
                  保存设置
                </el-button>
                <el-button @click="resetSecuritySettings">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>

        <!-- 通知设置 -->
        <el-tab-pane label="通知设置" name="notification">
          <div class="tab-content">
            <el-form :model="notificationSettings" :rules="notificationRules" ref="notificationFormRef" label-width="150px">
              <el-divider content-position="left">邮件通知</el-divider>
              
              <el-form-item label="SMTP服务器" prop="smtpServer">
                <el-input v-model="notificationSettings.smtpServer" placeholder="请输入SMTP服务器地址" />
              </el-form-item>
              
              <el-form-item label="SMTP端口" prop="smtpPort">
                <el-input-number
                  v-model="notificationSettings.smtpPort"
                  :min="1"
                  :max="65535"
                  style="width: 100%"
                />
              </el-form-item>
              
              <el-form-item label="发件人邮箱" prop="senderEmail">
                <el-input v-model="notificationSettings.senderEmail" placeholder="请输入发件人邮箱" />
              </el-form-item>
              
              <el-form-item label="邮箱密码" prop="emailPassword">
                <el-input
                  v-model="notificationSettings.emailPassword"
                  type="password"
                  placeholder="请输入邮箱密码"
                  show-password
                />
              </el-form-item>
              
              <el-form-item label="启用SSL" prop="enableSSL">
                <el-switch v-model="notificationSettings.enableSSL" />
              </el-form-item>
              
              <el-divider content-position="left">短信通知</el-divider>
              
              <el-form-item label="短信服务商" prop="smsProvider">
                <el-select v-model="notificationSettings.smsProvider" placeholder="请选择短信服务商" style="width: 100%">
                  <el-option label="阿里云" value="aliyun" />
                  <el-option label="腾讯云" value="tencent" />
                  <el-option label="华为云" value="huawei" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="Access Key" prop="smsAccessKey">
                <el-input v-model="notificationSettings.smsAccessKey" placeholder="请输入Access Key" />
              </el-form-item>
              
              <el-form-item label="Secret Key" prop="smsSecretKey">
                <el-input
                  v-model="notificationSettings.smsSecretKey"
                  type="password"
                  placeholder="请输入Secret Key"
                  show-password
                />
              </el-form-item>
              
              <el-divider content-position="left">通知规则</el-divider>
              
              <el-form-item label="库存预警通知" prop="stockWarningNotification">
                <el-switch v-model="notificationSettings.stockWarningNotification" />
              </el-form-item>
              
              <el-form-item label="订单状态通知" prop="orderStatusNotification">
                <el-switch v-model="notificationSettings.orderStatusNotification" />
              </el-form-item>
              
              <el-form-item label="审批通知" prop="approvalNotification">
                <el-switch v-model="notificationSettings.approvalNotification" />
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" @click="saveNotificationSettings" :loading="saveLoading">
                  保存设置
                </el-button>
                <el-button @click="resetNotificationSettings">重置</el-button>
                <el-button type="success" @click="testNotification">测试通知</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>

        <!-- 数据备份 -->
        <el-tab-pane label="数据备份" name="backup">
          <div class="tab-content">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-card class="backup-card">
                  <template #header>
                    <div class="card-header">
                      <span>自动备份设置</span>
                      <el-switch v-model="backupSettings.autoBackup" />
                    </div>
                  </template>
                  <el-form :model="backupSettings" label-width="120px">
                    <el-form-item label="备份频率">
                      <el-select v-model="backupSettings.frequency" style="width: 100%">
                        <el-option label="每日" value="daily" />
                        <el-option label="每周" value="weekly" />
                        <el-option label="每月" value="monthly" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="备份时间">
                      <el-time-picker
                        v-model="backupSettings.time"
                        format="HH:mm"
                        value-format="HH:mm"
                        style="width: 100%"
                      />
                    </el-form-item>
                    <el-form-item label="保留天数">
                      <el-input-number
                        v-model="backupSettings.retentionDays"
                        :min="1"
                        :max="365"
                        style="width: 100%"
                      />
                    </el-form-item>
                    <el-form-item label="备份路径">
                      <el-input v-model="backupSettings.backupPath" placeholder="请输入备份路径" />
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" @click="saveBackupSettings" :loading="saveLoading">
                        保存设置
                      </el-button>
                    </el-form-item>
                  </el-form>
                </el-card>
              </el-col>
              
              <el-col :span="12">
                <el-card class="backup-card">
                  <template #header>
                    <span>手动备份</span>
                  </template>
                  <div class="backup-content">
                    <p>立即创建系统数据备份</p>
                    <el-button type="success" @click="createBackup" :loading="backupLoading">
                      <el-icon><Download /></el-icon>
                      创建备份
                    </el-button>
                  </div>
                </el-card>
              </el-col>
            </el-row>
            
            <el-row :gutter="20" style="margin-top: 20px;">
              <el-col :span="24">
                <el-card class="backup-card">
                  <template #header>
                    <span>备份历史</span>
                  </template>
                  <el-table :data="backupHistory" border>
                    <el-table-column prop="name" label="备份名称" width="200" />
                    <el-table-column prop="size" label="文件大小" width="120" />
                    <el-table-column prop="createTime" label="创建时间" width="180" />
                    <el-table-column prop="status" label="状态" width="100">
                      <template #default="{ row }">
                        <el-tag :type="row.status === '成功' ? 'success' : 'danger'">
                          {{ row.status }}
                        </el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="200">
                      <template #default="{ row }">
                        <el-button type="primary" size="small" @click="downloadBackup(row)">
                          下载
                        </el-button>
                        <el-button type="success" size="small" @click="restoreBackup(row)">
                          恢复
                        </el-button>
                        <el-button type="danger" size="small" @click="deleteBackup(row)">
                          删除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>

        <!-- 系统监控 -->
        <el-tab-pane label="系统监控" name="monitor">
          <div class="tab-content">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-card class="monitor-card">
                  <template #header>
                    <span>系统状态</span>
                  </template>
                  <div class="monitor-content">
                    <div class="status-item">
                      <span class="status-label">CPU使用率</span>
                      <el-progress :percentage="systemStatus.cpuUsage" :color="getProgressColor(systemStatus.cpuUsage)" />
                    </div>
                    <div class="status-item">
                      <span class="status-label">内存使用率</span>
                      <el-progress :percentage="systemStatus.memoryUsage" :color="getProgressColor(systemStatus.memoryUsage)" />
                    </div>
                    <div class="status-item">
                      <span class="status-label">磁盘使用率</span>
                      <el-progress :percentage="systemStatus.diskUsage" :color="getProgressColor(systemStatus.diskUsage)" />
                    </div>
                    <div class="status-item">
                      <span class="status-label">网络状态</span>
                      <el-tag :type="systemStatus.networkStatus === '正常' ? 'success' : 'danger'">
                        {{ systemStatus.networkStatus }}
                      </el-tag>
                    </div>
                  </div>
                </el-card>
              </el-col>
              
              <el-col :span="8">
                <el-card class="monitor-card">
                  <template #header>
                    <span>数据库状态</span>
                  </template>
                  <div class="monitor-content">
                    <div class="status-item">
                      <span class="status-label">连接数</span>
                      <span class="status-value">{{ systemStatus.dbConnections }}/100</span>
                    </div>
                    <div class="status-item">
                      <span class="status-label">查询响应时间</span>
                      <span class="status-value">{{ systemStatus.dbResponseTime }}ms</span>
                    </div>
                    <div class="status-item">
                      <span class="status-label">数据库大小</span>
                      <span class="status-value">{{ systemStatus.dbSize }}MB</span>
                    </div>
                    <div class="status-item">
                      <span class="status-label">状态</span>
                      <el-tag :type="systemStatus.dbStatus === '正常' ? 'success' : 'danger'">
                        {{ systemStatus.dbStatus }}
                      </el-tag>
                    </div>
                  </div>
                </el-card>
              </el-col>
              
              <el-col :span="8">
                <el-card class="monitor-card">
                  <template #header>
                    <span>应用状态</span>
                  </template>
                  <div class="monitor-content">
                    <div class="status-item">
                      <span class="status-label">在线用户</span>
                      <span class="status-value">{{ systemStatus.onlineUsers }}</span>
                    </div>
                    <div class="status-item">
                      <span class="status-label">今日访问量</span>
                      <span class="status-value">{{ systemStatus.todayVisits }}</span>
                    </div>
                    <div class="status-item">
                      <span class="status-label">系统运行时间</span>
                      <span class="status-value">{{ systemStatus.uptime }}</span>
                    </div>
                    <div class="status-item">
                      <span class="status-label">版本</span>
                      <span class="status-value">{{ systemStatus.version }}</span>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
            
            <el-row :gutter="20" style="margin-top: 20px;">
              <el-col :span="24">
                <el-card class="monitor-card">
                  <template #header>
                    <div class="card-header">
                      <span>系统日志</span>
                      <el-button type="primary" size="small" @click="refreshLogs">
                        <el-icon><Refresh /></el-icon>
                        刷新
                      </el-button>
                    </div>
                  </template>
                  <el-table :data="systemLogs" border max-height="300">
                    <el-table-column prop="time" label="时间" width="180" />
                    <el-table-column prop="level" label="级别" width="80">
                      <template #default="{ row }">
                        <el-tag :type="getLogLevelType(row.level)" size="small">
                          {{ row.level }}
                        </el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column prop="module" label="模块" width="120" />
                    <el-table-column prop="message" label="消息" />
                    <el-table-column prop="user" label="用户" width="100" />
                  </el-table>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>

        <!-- 导航设置 -->
        <el-tab-pane label="导航设置" name="navigation">
          <div class="tab-content">
            <el-form :model="navigationSettings" :rules="navigationRules" ref="navigationFormRef" label-width="150px">
              <el-divider content-position="left">导航方式</el-divider>
              
              <el-form-item label="当前导航方式" prop="navigationMode">
                <el-select 
                  v-model="navigationSettings.navigationMode" 
                  placeholder="请选择导航方式" 
                  style="width: 100%"
                  @change="handleNavigationModeChange"
                >
                  <el-option
                    v-for="mode in navigationModes"
                    :key="mode.value"
                    :label="mode.name"
                    :value="mode.value"
                  >
                    <div style="display: flex; align-items: center; justify-content: space-between;">
                      <span>{{ mode.name }}</span>
                      <el-tag v-if="mode.badge" :type="getBadgeType(mode.badge)" size="small">
                        {{ mode.badge }}
                      </el-tag>
                    </div>
                  </el-option>
                </el-select>
                <span class="form-tip">选择您喜欢的导航方式</span>
              </el-form-item>
              
              <el-form-item label="导航方式预览">
                <div class="navigation-preview">
                  <div
                    v-for="mode in navigationModes"
                    :key="mode.value"
                    class="navigation-mode-card"
                    :class="{ active: navigationSettings.navigationMode === mode.value }"
                    @click="selectNavigationMode(mode.value)"
                  >
                    <div class="mode-header">
                      <div class="mode-name">{{ mode.name }}</div>
                      <el-tag v-if="mode.badge" :type="getBadgeType(mode.badge)" size="small">
                        {{ mode.badge }}
                      </el-tag>
                    </div>
                    <div class="mode-description">{{ mode.description }}</div>
                    <div class="mode-features">
                      <el-tag
                        v-for="feature in mode.features"
                        :key="feature"
                        size="small"
                        effect="plain"
                        style="margin-right: 4px; margin-bottom: 4px;"
                      >
                        {{ feature }}
                      </el-tag>
                    </div>
                  </div>
                </div>
              </el-form-item>
              
              <el-divider content-position="left">导航设置</el-divider>
              
              <el-form-item label="显示侧边栏" prop="showSidebar">
                <el-switch v-model="navigationSettings.showSidebar" />
                <span class="form-tip">是否显示侧边栏导航</span>
              </el-form-item>
              
              <el-form-item label="侧边栏宽度" prop="sidebarWidth">
                <el-slider
                  v-model="navigationSettings.sidebarWidth"
                  :min="200"
                  :max="320"
                  show-input
                  :show-input-controls="false"
                  style="width: 100%"
                />
                <span class="form-tip">侧边栏宽度（像素）</span>
              </el-form-item>
              
              <el-form-item label="显示面包屑" prop="showBreadcrumb">
                <el-switch v-model="navigationSettings.showBreadcrumb" />
                <span class="form-tip">是否显示面包屑导航</span>
              </el-form-item>
              
              <el-form-item label="显示标签页" prop="showTabs">
                <el-switch v-model="navigationSettings.showTabs" />
                <span class="form-tip">是否显示多标签页</span>
              </el-form-item>
              
              <el-form-item label="固定顶部" prop="fixedHeader">
                <el-switch v-model="navigationSettings.fixedHeader" />
                <span class="form-tip">是否固定顶部导航栏</span>
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" @click="saveNavigationSettings" :loading="saveLoading">
                  保存设置
                </el-button>
                <el-button @click="resetNavigationSettings">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>

        <!-- AI设置 -->
        <el-tab-pane label="AI设置" name="ai">
          <div class="tab-content">
            <el-form :model="aiSettings" :rules="aiRules" ref="aiFormRef" label-width="150px">
              <el-divider content-position="left">模型配置</el-divider>
              
              <el-form-item label="AI模型" prop="aiModel">
                <el-select v-model="aiSettings.aiModel" placeholder="请选择AI模型" style="width: 100%">
                  <el-option
                    v-for="model in aiModels"
                    :key="model.value"
                    :label="model.label"
                    :value="model.value"
                  >
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                      <span>{{ model.label }}</span>
                      <el-tag v-if="model.tag" :type="model.tagType" size="small">{{ model.tag }}</el-tag>
                    </div>
                  </el-option>
                </el-select>
                <span class="form-tip">选择使用的AI模型</span>
              </el-form-item>
              
              <el-form-item label="WebSocket地址" prop="aiUrl">
                <el-input v-model="aiSettings.aiUrl" placeholder="请输入WebSocket地址" />
                <span class="form-tip">AI服务的WebSocket连接地址</span>
              </el-form-item>

              <el-form-item label="API密钥" prop="apiKey">
                <el-input 
                  v-model="aiSettings.apiKey" 
                  type="password" 
                  placeholder="请输入API密钥（可选）"
                  show-password
                />
                <span class="form-tip">部分模型需要API密钥认证</span>
              </el-form-item>

              <el-divider content-position="left">对话参数</el-divider>
              
              <el-form-item label="Temperature" prop="temperature">
                <el-slider
                  v-model="aiSettings.temperature"
                  :min="0"
                  :max="2"
                  :step="0.1"
                  show-input
                  :show-input-controls="false"
                  style="width: 100%"
                />
                <span class="form-tip">控制输出的随机性，值越高越随机（0-2）</span>
              </el-form-item>

              <el-form-item label="Max Tokens" prop="maxTokens">
                <el-input-number
                  v-model="aiSettings.maxTokens"
                  :min="100"
                  :max="4000"
                  :step="100"
                  style="width: 100%"
                />
                <span class="form-tip">最大生成token数（100-4000）</span>
              </el-form-item>

              <el-form-item label="Top P" prop="topP">
                <el-slider
                  v-model="aiSettings.topP"
                  :min="0"
                  :max="1"
                  :step="0.05"
                  show-input
                  :show-input-controls="false"
                  style="width: 100%"
                />
                <span class="form-tip">核采样参数，控制输出的多样性（0-1）</span>
              </el-form-item>

              <el-form-item label="Presence Penalty" prop="presencePenalty">
                <el-slider
                  v-model="aiSettings.presencePenalty"
                  :min="-2"
                  :max="2"
                  :step="0.1"
                  show-input
                  :show-input-controls="false"
                  style="width: 100%"
                />
                <span class="form-tip">降低重复话题的惩罚（-2到2）</span>
              </el-form-item>

              <el-divider content-position="left">功能设置</el-divider>

              <el-form-item label="启用语音输入" prop="enableVoiceInput">
                <el-switch v-model="aiSettings.enableVoiceInput" />
                <span class="form-tip">是否启用语音输入功能</span>
              </el-form-item>

              <el-form-item label="启用Markdown渲染" prop="enableMarkdown">
                <el-switch v-model="aiSettings.enableMarkdown" />
                <span class="form-tip">是否启用Markdown格式渲染</span>
              </el-form-item>

              <el-form-item label="启用代码高亮" prop="enableCodeHighlight">
                <el-switch v-model="aiSettings.enableCodeHighlight" />
                <span class="form-tip">是否启用代码语法高亮</span>
              </el-form-item>

              <el-form-item label="启用思维链" prop="enableReasoning">
                <el-switch v-model="aiSettings.enableReasoning" />
                <span class="form-tip">显示AI思考过程</span>
              </el-form-item>

              <el-form-item label="自动滚动" prop="autoScroll">
                <el-switch v-model="aiSettings.autoScroll" />
                <span class="form-tip">消息发送后自动滚动到底部</span>
              </el-form-item>

              <el-divider content-position="left">系统提示词</el-divider>

              <el-form-item label="系统提示词" prop="systemPrompt">
                <el-input
                  v-model="aiSettings.systemPrompt"
                  type="textarea"
                  :rows="6"
                  placeholder="请输入系统提示词，用于定义AI的角色和行为..."
                />
                <span class="form-tip">自定义AI助手的角色和对话风格</span>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="saveAiSettings" :loading="saveLoading">
                  保存设置
                </el-button>
                <el-button @click="resetAiSettings">重置</el-button>
                <el-button @click="testAiConnection" :loading="testLoading">
                  测试连接
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>

        <!-- 系统维护 -->
        <el-tab-pane label="系统维护" name="maintenance">
          <div class="tab-content">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-card class="maintenance-card">
                  <template #header>
                    <span>缓存管理</span>
                  </template>
                  <div class="maintenance-content">
                    <p>清理系统缓存，提高系统性能</p>
                    <el-button type="primary" @click="clearCache" :loading="maintenanceLoading">
                      清理缓存
                    </el-button>
                  </div>
                </el-card>
              </el-col>
              
              <el-col :span="12">
                <el-card class="maintenance-card">
                  <template #header>
                    <span>日志管理</span>
                  </template>
                  <div class="maintenance-content">
                    <p>清理系统日志，释放存储空间</p>
                    <el-button type="warning" @click="clearLogs" :loading="maintenanceLoading">
                      清理日志
                    </el-button>
                  </div>
                </el-card>
              </el-col>
            </el-row>
            
            <el-row :gutter="20" style="margin-top: 20px;">
              <el-col :span="12">
                <el-card class="maintenance-card">
                  <template #header>
                    <span>数据统计</span>
                  </template>
                  <div class="maintenance-content">
                    <p>重新计算数据统计，确保数据准确性</p>
                    <el-button type="info" @click="recalculateStats" :loading="maintenanceLoading">
                      重新计算
                    </el-button>
                  </div>
                </el-card>
              </el-col>
              
              <el-col :span="12">
                <el-card class="maintenance-card">
                  <template #header>
                    <span>系统重启</span>
                  </template>
                  <div class="maintenance-content">
                    <p>重启系统服务，应用最新配置</p>
                    <el-button type="danger" @click="restartSystem" :loading="maintenanceLoading">
                      重启系统
                    </el-button>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useNavigationStore } from '@/stores/navigation'
import { keyUser, valueUser } from '@/api/data'

// 响应式数据
const activeTab = ref('basic')
const saveLoading = ref(false)
const maintenanceLoading = ref(false)
const backupLoading = ref(false)

// 表单引用
const basicFormRef = ref()
const businessFormRef = ref()
const securityFormRef = ref()
const notificationFormRef = ref()
const navigationFormRef = ref()
const aiFormRef = ref()

// AI相关状态
const testLoading = ref(false)

// 基本设置
const basicSettings = reactive({
  systemName: '大型ERP管理系统',
  systemVersion: '1.0.0',
  companyName: '示例科技有限公司',
  companyAddress: '北京市朝阳区科技园区',
  companyPhone: '400-123-4567',
  companyEmail: 'contact@example.com',
  companyWebsite: 'https://www.example.com',
  systemLogo: ''
})

// 业务设置
const businessSettings = reactive({
  defaultWarehouse: '1',
  stockWarningThreshold: 10,
  autoGenerateCode: true,
  orderPrefix: 'PO',
  orderValidityDays: 30,
  autoConfirmOrder: false,
  defaultCurrency: 'CNY',
  taxRate: 13.00
})

// 安全设置
const securitySettings = reactive({
  passwordMinLength: 8,
  passwordComplexity: ['uppercase', 'lowercase', 'numbers'],
  passwordExpiryDays: 90,
  loginLockEnabled: true,
  maxLoginAttempts: 5,
  lockoutDuration: 30,
  sessionTimeout: 120,
  dataEncryption: true,
  operationLog: true
})

// 通知设置
const notificationSettings = reactive({
  smtpServer: 'smtp.example.com',
  smtpPort: 587,
  senderEmail: 'noreply@example.com',
  emailPassword: '',
  enableSSL: true,
  smsProvider: 'aliyun',
  smsAccessKey: '',
  smsSecretKey: '',
  stockWarningNotification: true,
  orderStatusNotification: true,
  approvalNotification: true
})

// 备份设置
const backupSettings = reactive({
  autoBackup: true,
  frequency: 'daily',
  time: '02:00',
  retentionDays: 30,
  backupPath: '/backup'
})

// 导航设置
const navigationSettings = reactive({
  navigationMode: 'classic',
  showSidebar: true,
  sidebarWidth: 240,
  showBreadcrumb: true,
  showTabs: true,
  fixedHeader: true
})

// AI设置
const aiSettings = reactive({
  aiModel: '',
  aiUrl: 'wss://adminstore.saas.nbsaas.com/websocket',
  apiKey: '',
  temperature: 0.7,
  maxTokens: 2000,
  topP: 1.0,
  presencePenalty: 0.0,
  enableVoiceInput: true,
  enableMarkdown: true,
  enableCodeHighlight: true,
  enableReasoning: true,
  autoScroll: true,
  systemPrompt: '你是一个专业的ERP系统AI助手。请用清晰、友好的语言回答用户的问题，并提供实用的建议和解决方案。'
})

// AI模型列表
const aiModels = ref([
  {
    value: '',
    label: '默认模型',
    tag: null,
    tagType: null
  },
  {
    value: 'gpt-3.5-turbo',
    label: 'GPT-3.5 Turbo',
    tag: '推荐',
    tagType: 'success'
  },
  {
    value: 'gpt-4',
    label: 'GPT-4',
    tag: '最新',
    tagType: 'danger'
  },
  {
    value: 'gpt-4-turbo',
    label: 'GPT-4 Turbo',
    tag: '性能',
    tagType: 'warning'
  },
  {
    value: 'claude-3-opus',
    label: 'Claude 3 Opus',
    tag: 'Alight',
    tagType: 'info'
  },
  {
    value: 'claude-3-sonnet',
    label: 'Claude 3 Sonnet',
    tag: '平衡',
    tagType: 'info'
  }
])

// 导航方式列表
const navigationModes = ref([
  {
    value: 'classic',
    name: '经典导航',
    description: '传统的左侧边栏导航，适合层级较深的菜单结构',
    features: ['左侧边栏', '多级菜单', '可折叠'],
    badge: null
  },
  {
    value: 'topbar',
    name: '顶部导航',
    description: '顶部一级菜单 + 左侧二级菜单，适合模块化应用',
    features: ['顶部导航', '侧边栏', '模块化'],
    badge: null
  },
  {
    value: 'workspace',
    name: '工作台模式',
    description: '卡片式布局，适合日常高频操作',
    features: ['卡片布局', '快捷入口', '数据概览'],
    badge: null
  },
  {
    value: 'command',
    name: '命令面板',
    description: '快捷键驱动 + 命令搜索，适合高效操作',
    features: ['命令搜索', '快捷键', '快速访问'],
    badge: null
  },
  {
    value: 'pie-menu',
    name: '圆形菜单',
    description: '创新的圆形菜单导航，炫酷高效',
    features: ['圆形菜单', '动画效果', '创新交互'],
    badge: 'NEW'
  },
  {
    value: 'dock',
    name: 'Dock栏导航',
    description: 'macOS风格的Dock栏，优雅美观',
    features: ['Dock栏', 'macOS风格', '图标预览'],
    badge: 'NEW'
  },
  {
    value: 'card',
    name: '卡片式导航',
    description: '大卡片展示，视觉冲击力强',
    features: ['大卡片', '视觉冲击', '直观展示'],
    badge: 'NEW'
  },
  {
    value: 'smart-search',
    name: '智能搜索',
    description: '搜索驱动的导航方式，极速访问',
    features: ['全局搜索', '智能推荐', '快速查找'],
    badge: 'HOT'
  },
  {
    value: 'win10',
    name: 'Windows 10 风格',
    description: '仿Windows 10开始菜单和任务栏',
    features: ['Win10风格', '开始菜单', '任务栏'],
    badge: 'NEW'
  },
  {
    value: 'win8',
    name: 'Windows 8 风格',
    description: '仿Windows 8开始屏幕和磁贴',
    features: ['Win8风格', '磁贴布局', '动态效果'],
    badge: 'NEW'
  },
  {
    value: 'floating-panel',
    name: '浮动面板',
    description: '可拖拽的智能浮动导航面板',
    features: ['浮动面板', '可拖拽', '智能导航'],
    badge: '创新'
  },
  {
    value: 'gesture',
    name: '手势导航',
    description: '触摸手势和圆形菜单导航',
    features: ['手势操作', '触摸优化', '圆形菜单'],
    badge: '创新'
  },
  {
    value: 'ai-assistant',
    name: 'AI助手',
    description: '智能AI助手驱动的导航体验',
    features: ['AI助手', '智能推荐', '语音导航'],
    badge: '未来'
  },
  {
    value: 'intelligent',
    name: '智能导航',
    description: 'AI驱动的智能导航系统，专为大型ERP优化',
    features: ['智能导航', 'AI驱动', 'ERP优化'],
    badge: '推荐'
  },
  {
    value: 'smart-navigation',
    name: '智能导航系统',
    description: '左侧主菜单 + 右侧子菜单的智能导航',
    features: ['双栏布局', '主菜单', '子菜单'],
    badge: 'NEW'
  },
  {
    value: 'mac-launchpad',
    name: 'Mac Launchpad',
    description: 'macOS Launchpad风格的网格导航，支持左右滚动分页',
    features: ['Mac风格', '左右滚动', '分页展示'],
    badge: 'NEW'
  }
])

// 系统状态
const systemStatus = reactive({
  cpuUsage: 45,
  memoryUsage: 68,
  diskUsage: 32,
  networkStatus: '正常',
  dbConnections: 25,
  dbResponseTime: 120,
  dbSize: 1024,
  dbStatus: '正常',
  onlineUsers: 12,
  todayVisits: 156,
  uptime: '15天 8小时',
  version: '1.0.0'
})

// 备份历史
const backupHistory = ref([
  {
    name: 'backup_20240115_020000.sql',
    size: '125MB',
    createTime: '2024-01-15 02:00:00',
    status: '成功'
  },
  {
    name: 'backup_20240114_020000.sql',
    size: '123MB',
    createTime: '2024-01-14 02:00:00',
    status: '成功'
  },
  {
    name: 'backup_20240113_020000.sql',
    size: '121MB',
    createTime: '2024-01-13 02:00:00',
    status: '成功'
  }
])

// 系统日志
const systemLogs = ref([
  {
    time: '2024-01-15 14:30:25',
    level: 'INFO',
    module: '用户管理',
    message: '用户登录成功',
    user: 'admin'
  },
  {
    time: '2024-01-15 14:28:15',
    level: 'WARN',
    module: '库存管理',
    message: '商品库存不足预警',
    user: 'system'
  },
  {
    time: '2024-01-15 14:25:10',
    level: 'ERROR',
    module: '订单管理',
    message: '订单处理失败',
    user: 'user1'
  },
  {
    time: '2024-01-15 14:20:05',
    level: 'INFO',
    module: '系统监控',
    message: '系统状态检查完成',
    user: 'system'
  }
])

// 表单验证规则
const basicRules = {
  systemName: [
    { required: true, message: '请输入系统名称', trigger: 'blur' }
  ],
  companyName: [
    { required: true, message: '请输入公司名称', trigger: 'blur' }
  ],
  companyEmail: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

const businessRules = {
  defaultWarehouse: [
    { required: true, message: '请选择默认仓库', trigger: 'change' }
  ],
  orderPrefix: [
    { required: true, message: '请输入订单号前缀', trigger: 'blur' }
  ],
  defaultCurrency: [
    { required: true, message: '请选择默认币种', trigger: 'change' }
  ]
}

const securityRules = {
  passwordMinLength: [
    { required: true, message: '请输入密码最小长度', trigger: 'blur' }
  ],
  maxLoginAttempts: [
    { required: true, message: '请输入最大失败次数', trigger: 'blur' }
  ]
}

const notificationRules = {
  smtpServer: [
    { required: true, message: '请输入SMTP服务器', trigger: 'blur' }
  ],
  senderEmail: [
    { required: true, message: '请输入发件人邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

const navigationRules = {
  navigationMode: [
    { required: true, message: '请选择导航方式', trigger: 'change' }
  ]
}

const aiRules = {
  aiUrl: [
    { required: true, message: '请输入WebSocket地址', trigger: 'blur' }
  ]
}

// 上传配置
const uploadUrl = '/api/upload'

// 方法
const handleTabChange = (tabName) => {
  activeTab.value = tabName
}

const handleLogoSuccess = (response) => {
  basicSettings.systemLogo = response.url
  ElMessage.success('Logo上传成功')
}

const beforeLogoUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('Logo只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('Logo大小不能超过 2MB!')
    return false
  }
  return true
}

const saveBasicSettings = async () => {
  if (!basicFormRef.value) return
  
  try {
    await basicFormRef.value.validate()
    saveLoading.value = true
    
    // 保存到API
    try {
      await valueUser('system_basic_settings', JSON.stringify(basicSettings))
    } catch (error) {
      console.error('保存到服务器失败:', error)
      // API失败时保存到本地存储作为备选
      localStorage.setItem('basicSettings', JSON.stringify(basicSettings))
    }
    
    // 同时保存到本地存储（向后兼容）
    localStorage.setItem('basicSettings', JSON.stringify(basicSettings))
    
    ElMessage.success('基本设置保存成功')
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    saveLoading.value = false
  }
}

const saveBusinessSettings = async () => {
  if (!businessFormRef.value) return
  
  try {
    await businessFormRef.value.validate()
    saveLoading.value = true
    
    // 保存到API
    try {
      await valueUser('system_business_settings', JSON.stringify(businessSettings))
    } catch (error) {
      console.error('保存到服务器失败:', error)
      // API失败时保存到本地存储作为备选
      localStorage.setItem('businessSettings', JSON.stringify(businessSettings))
    }
    
    // 同时保存到本地存储（向后兼容）
    localStorage.setItem('businessSettings', JSON.stringify(businessSettings))
    
    ElMessage.success('业务设置保存成功')
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    saveLoading.value = false
  }
}

const saveSecuritySettings = async () => {
  if (!securityFormRef.value) return
  
  try {
    await securityFormRef.value.validate()
    saveLoading.value = true
    
    // 保存到API
    try {
      await valueUser('system_security_settings', JSON.stringify(securitySettings))
    } catch (error) {
      console.error('保存到服务器失败:', error)
      // API失败时保存到本地存储作为备选
      localStorage.setItem('securitySettings', JSON.stringify(securitySettings))
    }
    
    // 同时保存到本地存储（向后兼容）
    localStorage.setItem('securitySettings', JSON.stringify(securitySettings))
    
    ElMessage.success('安全设置保存成功')
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    saveLoading.value = false
  }
}

const saveNotificationSettings = async () => {
  if (!notificationFormRef.value) return
  
  try {
    await notificationFormRef.value.validate()
    saveLoading.value = true
    
    // 保存到API
    try {
      await valueUser('system_notification_settings', JSON.stringify(notificationSettings))
    } catch (error) {
      console.error('保存到服务器失败:', error)
      // API失败时保存到本地存储作为备选
      localStorage.setItem('notificationSettings', JSON.stringify(notificationSettings))
    }
    
    // 同时保存到本地存储（向后兼容）
    localStorage.setItem('notificationSettings', JSON.stringify(notificationSettings))
    
    ElMessage.success('通知设置保存成功')
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    saveLoading.value = false
  }
}

const resetBasicSettings = () => {
  Object.assign(basicSettings, {
    systemName: '大型ERP管理系统',
    systemVersion: '1.0.0',
    companyName: '示例科技有限公司',
    companyAddress: '北京市朝阳区科技园区',
    companyPhone: '400-123-4567',
    companyEmail: 'contact@example.com',
    companyWebsite: 'https://www.example.com',
    systemLogo: ''
  })
  basicFormRef.value?.clearValidate()
}

const resetBusinessSettings = () => {
  Object.assign(businessSettings, {
    defaultWarehouse: '1',
    stockWarningThreshold: 10,
    autoGenerateCode: true,
    orderPrefix: 'PO',
    orderValidityDays: 30,
    autoConfirmOrder: false,
    defaultCurrency: 'CNY',
    taxRate: 13.00
  })
  businessFormRef.value?.clearValidate()
}

const resetSecuritySettings = () => {
  Object.assign(securitySettings, {
    passwordMinLength: 8,
    passwordComplexity: ['uppercase', 'lowercase', 'numbers'],
    passwordExpiryDays: 90,
    loginLockEnabled: true,
    maxLoginAttempts: 5,
    lockoutDuration: 30,
    sessionTimeout: 120,
    dataEncryption: true,
    operationLog: true
  })
  securityFormRef.value?.clearValidate()
}

const resetNotificationSettings = () => {
  Object.assign(notificationSettings, {
    smtpServer: 'smtp.example.com',
    smtpPort: 587,
    senderEmail: 'noreply@example.com',
    emailPassword: '',
    enableSSL: true,
    smsProvider: 'aliyun',
    smsAccessKey: '',
    smsSecretKey: '',
    stockWarningNotification: true,
    orderStatusNotification: true,
    approvalNotification: true
  })
  notificationFormRef.value?.clearValidate()
}

const testNotification = async () => {
  try {
    await ElMessageBox.confirm('确定要发送测试通知吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟发送测试通知
    ElMessage.success('测试通知发送成功')
  } catch {
    // 用户取消操作
  }
}

const clearCache = async () => {
  try {
    await ElMessageBox.confirm('确定要清理系统缓存吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    maintenanceLoading.value = true
    
    // 模拟清理缓存
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    ElMessage.success('缓存清理完成')
  } catch {
    // 用户取消操作
  } finally {
    maintenanceLoading.value = false
  }
}

const clearLogs = async () => {
  try {
    await ElMessageBox.confirm('确定要清理系统日志吗？此操作不可恢复！', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    maintenanceLoading.value = true
    
    // 模拟清理日志
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    ElMessage.success('日志清理完成')
  } catch {
    // 用户取消操作
  } finally {
    maintenanceLoading.value = false
  }
}

const recalculateStats = async () => {
  try {
    await ElMessageBox.confirm('确定要重新计算数据统计吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    maintenanceLoading.value = true
    
    // 模拟重新计算
    await new Promise(resolve => setTimeout(resolve, 3000))
    
    ElMessage.success('数据统计重新计算完成')
  } catch {
    // 用户取消操作
  } finally {
    maintenanceLoading.value = false
  }
}

const restartSystem = async () => {
  try {
    await ElMessageBox.confirm('确定要重启系统吗？这将中断所有用户会话！', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    })
    
    maintenanceLoading.value = true
    
    // 模拟重启系统
    await new Promise(resolve => setTimeout(resolve, 5000))
    
    ElMessage.success('系统重启完成')
  } catch {
    // 用户取消操作
  } finally {
    maintenanceLoading.value = false
  }
}

// 备份相关方法
const saveBackupSettings = async () => {
  try {
    saveLoading.value = true
    
    // 保存到API
    try {
      await valueUser('system_backup_settings', JSON.stringify(backupSettings))
    } catch (error) {
      console.error('保存到服务器失败:', error)
      // API失败时保存到本地存储作为备选
      localStorage.setItem('backupSettings', JSON.stringify(backupSettings))
    }
    
    // 同时保存到本地存储（向后兼容）
    localStorage.setItem('backupSettings', JSON.stringify(backupSettings))
    
    ElMessage.success('备份设置保存成功')
  } catch (error) {
    console.error('保存失败:', error)
  } finally {
    saveLoading.value = false
  }
}

const createBackup = async () => {
  try {
    await ElMessageBox.confirm('确定要创建数据备份吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    backupLoading.value = true
    
    // 模拟创建备份
    await new Promise(resolve => setTimeout(resolve, 3000))
    
    // 添加新的备份记录
    const newBackup = {
      name: `backup_${new Date().toISOString().slice(0, 19).replace(/[-:]/g, '').replace('T', '_')}.sql`,
      size: '126MB',
      createTime: new Date().toLocaleString(),
      status: '成功'
    }
    
    backupHistory.value.unshift(newBackup)
    
    ElMessage.success('数据备份创建成功')
  } catch {
    // 用户取消操作
  } finally {
    backupLoading.value = false
  }
}

const downloadBackup = (row) => {
  ElMessage.info(`下载备份文件: ${row.name}`)
}

const restoreBackup = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要恢复备份 ${row.name} 吗？这将覆盖当前数据！`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    })
    
    ElMessage.success('数据恢复成功')
  } catch {
    // 用户取消操作
  }
}

const deleteBackup = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除备份 ${row.name} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = backupHistory.value.findIndex(item => item.name === row.name)
    if (index > -1) {
      backupHistory.value.splice(index, 1)
      ElMessage.success('备份删除成功')
    }
  } catch {
    // 用户取消操作
  }
}

// 系统监控相关方法
const getProgressColor = (percentage) => {
  if (percentage < 50) return '#67c23a'
  if (percentage < 80) return '#e6a23c'
  return '#f56c6c'
}

const getLogLevelType = (level) => {
  const levelMap = {
    'INFO': 'success',
    'WARN': 'warning',
    'ERROR': 'danger',
    'DEBUG': 'info'
  }
  return levelMap[level] || 'info'
}

const refreshLogs = () => {
  // 模拟刷新日志
  const newLog = {
    time: new Date().toLocaleString(),
    level: 'INFO',
    module: '系统监控',
    message: '日志刷新完成',
    user: 'system'
  }
  
  systemLogs.value.unshift(newLog)
  
  // 保持日志数量不超过10条
  if (systemLogs.value.length > 10) {
    systemLogs.value = systemLogs.value.slice(0, 10)
  }
  
  ElMessage.success('日志刷新完成')
}

// 导航设置相关方法
const navigationStore = useNavigationStore()

const getBadgeType = (badge) => {
  const badgeMap = {
    'NEW': 'success',
    'HOT': 'danger',
    '推荐': 'warning',
    '创新': 'info',
    '未来': 'warning'
  }
  return badgeMap[badge] || 'info'
}

const selectNavigationMode = (mode) => {
  navigationSettings.navigationMode = mode
}

const handleNavigationModeChange = async (mode) => {
  try {
    // 立即更新导航存储
    await navigationStore.setMode(mode)
    ElMessage.success(`已切换到${navigationModes.value.find(m => m.value === mode)?.name}`)
  } catch (error) {
    console.error('切换导航方式失败:', error)
    ElMessage.error('切换导航方式失败')
  }
}

const saveNavigationSettings = async () => {
  if (!navigationFormRef.value) return
  
  try {
    await navigationFormRef.value.validate()
    saveLoading.value = true
    
    // 更新导航存储
    await navigationStore.setMode(navigationSettings.navigationMode)
    await navigationStore.updateSettings({
      sidebarWidth: navigationSettings.sidebarWidth,
      showBreadcrumb: navigationSettings.showBreadcrumb,
      showTabs: navigationSettings.showTabs,
      fixedHeader: navigationSettings.fixedHeader
    })
    
    // 保存到API
    try {
      await valueUser('navigation_settings', JSON.stringify({
        mode: navigationSettings.navigationMode,
        settings: {
          sidebarWidth: navigationSettings.sidebarWidth,
          showBreadcrumb: navigationSettings.showBreadcrumb,
          showTabs: navigationSettings.showTabs,
          fixedHeader: navigationSettings.fixedHeader
        }
      }))
    } catch (error) {
      console.error('保存到服务器失败:', error)
      // 即使API失败，也显示成功（因为已经保存到store）
    }
    
    ElMessage.success('导航设置保存成功')
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    saveLoading.value = false
  }
}

const resetNavigationSettings = () => {
  Object.assign(navigationSettings, {
    navigationMode: 'classic',
    showSidebar: true,
    sidebarWidth: 240,
    showBreadcrumb: true,
    showTabs: true,
    fixedHeader: true
  })
  navigationFormRef.value?.clearValidate()
}

const saveAiSettings = async () => {
  if (!aiFormRef.value) return
  
  try {
    await aiFormRef.value.validate()
    saveLoading.value = true
    
    // 保存到API
    try {
      await valueUser('system_ai_settings', JSON.stringify(aiSettings))
    } catch (error) {
      console.error('保存到服务器失败:', error)
      localStorage.setItem('aiSettings', JSON.stringify(aiSettings))
    }
    
    // 同时保存到本地存储
    localStorage.setItem('aiSettings', JSON.stringify(aiSettings))
    
    // 更新全局配置
    if (window.DEFAULT_CONFIG) {
      window.DEFAULT_CONFIG.AI_URL = aiSettings.aiUrl
    }
    
    ElMessage.success('AI设置保存成功')
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    saveLoading.value = false
  }
}

const resetAiSettings = () => {
  Object.assign(aiSettings, {
    aiModel: '',
    aiUrl: 'wss://adminstore.saas.nbsaas.com/websocket',
    apiKey: '',
    temperature: 0.7,
    maxTokens: 2000,
    topP: 1.0,
    presencePenalty: 0.0,
    enableVoiceInput: true,
    enableMarkdown: true,
    enableCodeHighlight: true,
    enableReasoning: true,
    autoScroll: true,
    systemPrompt: '你是一个专业的ERP系统AI助手。请用清晰、友好的语言回答用户的问题，并提供实用的建议和解决方案。'
  })
  aiFormRef.value?.clearValidate()
}

const testAiConnection = async () => {
  if (!aiSettings.aiUrl) {
    ElMessage.warning('请先输入WebSocket地址')
    return
  }
  
  testLoading.value = true
  
  try {
    const ws = new WebSocket(aiSettings.aiUrl)
    
    ws.onopen = () => {
      ElMessage.success('AI连接测试成功')
      ws.close()
      testLoading.value = false
    }
    
    ws.onerror = () => {
      ElMessage.error('AI连接测试失败，请检查地址是否正确')
      testLoading.value = false
    }
    
    // 5秒超时
    setTimeout(() => {
      if (ws.readyState !== WebSocket.OPEN) {
        ws.close()
        ElMessage.error('连接超时，请检查网络或地址')
        testLoading.value = false
      }
    }, 5000)
  } catch (error) {
    console.error('连接测试失败:', error)
    ElMessage.error('连接测试失败: ' + error.message)
    testLoading.value = false
  }
}

// 生命周期
onMounted(async () => {
  // 加载所有设置
  await loadAllSettings()
})

// 加载所有设置
const loadAllSettings = async () => {
  // 并行加载所有设置
  await Promise.all([
    loadBasicSettings(),
    loadBusinessSettings(),
    loadSecuritySettings(),
    loadNotificationSettings(),
    loadBackupSettings(),
    loadNavigationSettings(),
    loadAiSettings()
  ])
}

// 加载基本设置
const loadBasicSettings = async () => {
  try {
    // 先从API加载
    try {
      const response = await keyUser('system_basic_settings')
      if (response && response.code === 200 && response.data) {
        let data = response.data
        if (typeof data === 'string') {
          data = JSON.parse(data)
        } else if (data.value) {
          data = JSON.parse(data.value)
        }
        Object.assign(basicSettings, data)
        return
      }
    } catch (error) {
      console.error('从API加载基本设置失败:', error)
    }
    
    // API失败时从本地存储加载
    const savedBasic = localStorage.getItem('basicSettings')
    if (savedBasic) {
      Object.assign(basicSettings, JSON.parse(savedBasic))
    }
  } catch (error) {
    console.error('加载基本设置失败:', error)
  }
}

// 加载业务设置
const loadBusinessSettings = async () => {
  try {
    // 先从API加载
    try {
      const response = await keyUser('system_business_settings')
      if (response && response.code === 200 && response.data) {
        let data = response.data
        if (typeof data === 'string') {
          data = JSON.parse(data)
        } else if (data.value) {
          data = JSON.parse(data.value)
        }
        Object.assign(businessSettings, data)
        return
      }
    } catch (error) {
      console.error('从API加载业务设置失败:', error)
    }
    
    // API失败时从本地存储加载
    const savedBusiness = localStorage.getItem('businessSettings')
    if (savedBusiness) {
      Object.assign(businessSettings, JSON.parse(savedBusiness))
    }
  } catch (error) {
    console.error('加载业务设置失败:', error)
  }
}

// 加载安全设置
const loadSecuritySettings = async () => {
  try {
    // 先从API加载
    try {
      const response = await keyUser('system_security_settings')
      if (response && response.code === 200 && response.data) {
        let data = response.data
        if (typeof data === 'string') {
          data = JSON.parse(data)
        } else if (data.value) {
          data = JSON.parse(data.value)
        }
        Object.assign(securitySettings, data)
        return
      }
    } catch (error) {
      console.error('从API加载安全设置失败:', error)
    }
    
    // API失败时从本地存储加载
    const savedSecurity = localStorage.getItem('securitySettings')
    if (savedSecurity) {
      Object.assign(securitySettings, JSON.parse(savedSecurity))
    }
  } catch (error) {
    console.error('加载安全设置失败:', error)
  }
}

// 加载通知设置
const loadNotificationSettings = async () => {
  try {
    // 先从API加载
    try {
      const response = await keyUser('system_notification_settings')
      if (response && response.code === 200 && response.data) {
        let data = response.data
        if (typeof data === 'string') {
          data = JSON.parse(data)
        } else if (data.value) {
          data = JSON.parse(data.value)
        }
        Object.assign(notificationSettings, data)
        return
      }
    } catch (error) {
      console.error('从API加载通知设置失败:', error)
    }
    
    // API失败时从本地存储加载
    const savedNotification = localStorage.getItem('notificationSettings')
    if (savedNotification) {
      Object.assign(notificationSettings, JSON.parse(savedNotification))
    }
  } catch (error) {
    console.error('加载通知设置失败:', error)
  }
}

// 加载备份设置
const loadBackupSettings = async () => {
  try {
    // 先从API加载
    try {
      const response = await keyUser('system_backup_settings')
      if (response && response.code === 200 && response.data) {
        let data = response.data
        if (typeof data === 'string') {
          data = JSON.parse(data)
        } else if (data.value) {
          data = JSON.parse(data.value)
        }
        Object.assign(backupSettings, data)
        return
      }
    } catch (error) {
      console.error('从API加载备份设置失败:', error)
    }
    
    // API失败时从本地存储加载
    const savedBackup = localStorage.getItem('backupSettings')
    if (savedBackup) {
      Object.assign(backupSettings, JSON.parse(savedBackup))
    }
  } catch (error) {
    console.error('加载备份设置失败:', error)
  }
}

// 加载导航设置
const loadNavigationSettings = async () => {
  try {
    // 先从导航存储加载
    const store = navigationStore
    navigationSettings.navigationMode = store.mode || 'classic'
    navigationSettings.showSidebar = true // 根据导航模式判断
    navigationSettings.sidebarWidth = store.settings?.sidebarWidth || 240
    navigationSettings.showBreadcrumb = store.settings?.showBreadcrumb ?? true
    navigationSettings.showTabs = store.settings?.showTabs ?? true
    navigationSettings.fixedHeader = store.settings?.fixedHeader ?? true
    
    // 从API加载
    try {
      const response = await keyUser('navigation_settings')
      if (response && response.code === 200 && response.data) {
        let data = response.data
        if (typeof data === 'string') {
          data = JSON.parse(data)
        } else if (data.value) {
          data = JSON.parse(data.value)
        }
        
        if (data.mode) {
          navigationSettings.navigationMode = data.mode
        }
        if (data.settings) {
          if (data.settings.sidebarWidth !== undefined) {
            navigationSettings.sidebarWidth = data.settings.sidebarWidth
          }
          if (data.settings.showBreadcrumb !== undefined) {
            navigationSettings.showBreadcrumb = data.settings.showBreadcrumb
          }
          if (data.settings.showTabs !== undefined) {
            navigationSettings.showTabs = data.settings.showTabs
          }
          if (data.settings.fixedHeader !== undefined) {
            navigationSettings.fixedHeader = data.settings.fixedHeader
          }
        }
      }
    } catch (error) {
      console.error('从API加载导航设置失败:', error)
      // API失败时使用store中的值
    }
  } catch (error) {
    console.error('加载导航设置失败:', error)
  }
}

// 加载AI设置
const loadAiSettings = async () => {
  try {
    // 先从API加载
    try {
      const response = await keyUser('system_ai_settings')
      if (response && response.code === 200 && response.data) {
        let data = response.data
        if (typeof data === 'string') {
          data = JSON.parse(data)
        } else if (data.value) {
          data = JSON.parse(data.value)
        }
        Object.assign(aiSettings, data)
        return
      }
    } catch (error) {
      console.error('从API加载AI设置失败:', error)
    }
    
    // API失败时从本地存储加载
    const savedAi = localStorage.getItem('aiSettings')
    if (savedAi) {
      Object.assign(aiSettings, JSON.parse(savedAi))
    } else {
      // 从配置文件加载默认值
      const DEFAULT_CONFIG = await import('@/config/index.js').then(m => m.default)
      if (DEFAULT_CONFIG && DEFAULT_CONFIG.AI_URL) {
        aiSettings.aiUrl = DEFAULT_CONFIG.AI_URL
      }
    }
  } catch (error) {
    console.error('加载AI设置失败:', error)
  }
}
</script>

<style scoped>
.settings-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.tab-content {
  padding: 20px 0;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-left: 8px;
}

.logo-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.logo-uploader:hover {
  border-color: #409EFF;
}

.logo-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.logo {
  width: 120px;
  height: 120px;
  display: block;
}

.maintenance-card {
  margin-bottom: 20px;
}

.maintenance-content {
  text-align: center;
  padding: 20px 0;
}

.maintenance-content p {
  margin-bottom: 20px;
  color: #606266;
}

.backup-card {
  margin-bottom: 20px;
}

.backup-content {
  text-align: center;
  padding: 20px 0;
}

.backup-content p {
  margin-bottom: 20px;
  color: #606266;
}

.monitor-card {
  margin-bottom: 20px;
}

.monitor-content {
  padding: 20px 0;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.status-label {
  font-size: 14px;
  color: #606266;
}

.status-value {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 导航设置样式 */
.navigation-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-top: 16px;
}

.navigation-mode-card {
  padding: 16px;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fff;
  flex: 1 1 280px;
  min-width: 280px;
  max-width: 400px;
}

.navigation-mode-card:hover {
  border-color: #409eff;
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.15);
}

.navigation-mode-card.active {
  border-color: #409eff;
  background: #ecf5ff;
}

.mode-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.mode-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.mode-description {
  font-size: 13px;
  color: #909399;
  line-height: 1.5;
  margin-bottom: 12px;
}

.mode-features {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}
</style>
